<template>
  <view class="fix-top-window">
    <view class="uni-header">
      <view class="uni-group flex items-center">
        <input
          class="uni-search flex-1"
          type="text"
          v-model="query"
          @confirm="handleSearch"
          :placeholder="t('common.placeholder.query')"
        />
        <button
          class="uni-button hide-on-phone"
          type="default"
          size="mini"
          @click="handleSearch"
        >
          {{ t("common.button.search") }}
        </button>
        <button
          class="uni-button"
          type="primary"
          size="mini"
          @click="handleNavigateTo('./add')"
        >
          {{ t("common.button.add") }}
        </button>
        <button
          class="uni-button"
          type="warn"
          size="mini"
          :disabled="!selectedIndexs.length"
          @click="handleBatchDelete"
        >
          {{ t("common.button.batchDelete") }}
        </button>
        <!-- #ifdef H5 -->
        <download-excel
          class="hide-on-phone"
          :fields="exportExcel.fields"
          :data="exportExcelData"
          :type="exportExcel.type"
          :name="exportExcel.filename"
        >
          <button class="uni-button" type="primary" size="mini">
            {{ t("common.button.exportExcel") }}
          </button>
        </download-excel>
        <!-- #endif -->
      </view>
    </view>
    <view class="uni-container">
      <uni-table
        ref="tableRef"
        :loading="loading"
        :emptyText="error || t('common.empty')"
        border
        stripe
        type="selection"
        @selection-change="handleSelectionChange"
      >
        <uni-tr>
          <uni-th
            align="center"
            filter-type="search"
            @filter-change="(e) => handleFilterChange(e, 'username')"
            sortable
            @sort-change="(e) => handleSortChange(e, 'username')"
          >
            用户名
          </uni-th>
          <uni-th
            align="center"
            filter-type="search"
            @filter-change="(e) => handleFilterChange(e, 'nickname')"
            sortable
            @sort-change="(e) => handleSortChange(e, 'nickname')"
          >
            用户昵称
          </uni-th>
          <uni-th
            align="center"
            filter-type="search"
            @filter-change="(e) => handleFilterChange(e, 'mobile')"
            sortable
            @sort-change="(e) => handleSortChange(e, 'mobile')"
          >
            手机号码
          </uni-th>
          <uni-th
            align="center"
            filter-type="select"
            :filter-data="statusFilterData"
            @filter-change="(e) => handleFilterChange(e, 'status')"
          >
            用户状态
          </uni-th>
          <uni-th
            align="center"
            filter-type="search"
            @filter-change="(e) => handleFilterChange(e, 'email')"
            sortable
            @sort-change="(e) => handleSortChange(e, 'email')"
          >
            邮箱
          </uni-th>
          <uni-th align="center">角色</uni-th>
          <uni-th align="center">可登录应用</uni-th>
          <uni-th
            align="center"
            filter-type="timestamp"
            @filter-change="(e) => handleFilterChange(e, 'last_login_date')"
            sortable
            @sort-change="(e) => handleSortChange(e, 'last_login_date')"
          >
            最后登录时间
          </uni-th>
          <uni-th align="center">操作</uni-th>
        </uni-tr>
        <uni-tr v-for="(item, index) in dataList" :key="item._id || index">
          <uni-td align="center">{{ item.username }}</uni-td>
          <uni-td align="center">{{ item.nickname }}</uni-td>
          <uni-td align="center">{{ item.mobile }}</uni-td>
          <uni-td align="center">{{ statusValueToText[item.status] }}</uni-td>
          <uni-td align="center">
            <uni-link
              :href="'mailto:' + item.email"
              :text="item.email"
            ></uni-link>
          </uni-td>
          <uni-td align="center">{{ item.role_display || item.role }}</uni-td>
          <uni-td align="center">
            <uni-link
              v-if="!item.dcloud_appid_display"
              :href="noAppidWhatShouldIDoLink"
            >
              未绑定可登录应用<view class="uni-icons-help"></view>
            </uni-link>
            {{ item.dcloud_appid_display || item.dcloud_appid }}
          </uni-td>
          <uni-td align="center">
            <uni-dateformat
              :threshold="[0, 0]"
              :date="item.last_login_date"
            ></uni-dateformat>
          </uni-td>
          <uni-td align="center">
            <view class="flex items-center justify-center">
              <button
                @click="handleNavigateTo('./edit?id=' + item._id, false)"
                class="uni-button"
                size="mini"
                type="primary"
              >
                {{ t("common.button.edit") }}
              </button>
              <button
                @click="handleConfirmDelete(item._id)"
                class="uni-button"
                size="mini"
                type="warn"
              >
                {{ t("common.button.delete") }}
              </button>
            </view>
          </uni-td>
        </uni-tr>
      </uni-table>
      <view class="uni-pagination-box">
        <uni-pagination
          show-iconn
          show-page-size
          :page-size="pagination.size"
          v-model="pagination.current"
          :total="pagination.count"
          @change="handlePageChanged"
          @pageSizeChange="handleChangeSize"
        />
      </view>
    </view>
    <!-- #ifndef H5 -->
    <fix-window />
    <!-- #endif -->
  </view>
</template>

<script setup>
import { ref, reactive, computed, getCurrentInstance } from "vue";
import { useI18n } from "vue-i18n";
import { enumConverter } from "../../../js_sdk/validator/uni-id-users.js";

// 国际化
const { t } = useI18n();

// 获取全局属性（uni-app 和 Vue 全局属性）
const instance = getCurrentInstance();
const vk = uni.vk; // vk 框架会自动挂载到 uni.vk
const $formatDate = instance?.appContext?.config?.globalProperties?.$formatDate; // 已通过 plugin.js 全局挂载

// 分页配置常量
const PAGE_SIZE = 20;
const PAGE_CURRENT = 1;

// 排序映射
const orderByMapping = {
  ascending: "asc",
  descending: "desc",
};

// 响应式数据
const dataList = ref([]);
const query = ref("");
const selectedIndexs = ref([]);
const loading = ref(false);
const error = ref("");
const tableRef = ref(null);

// 分页数据
const pagination = reactive({
  current: PAGE_CURRENT,
  size: PAGE_SIZE,
  count: 0,
});

// 查询参数
const queryParams = reactive({
  pageIndex: PAGE_CURRENT,
  pageSize: PAGE_SIZE,
  keyword: "",
  status: undefined,
  orderBy: "last_login_date",
  orderType: "desc",
});

// 状态筛选数据
const statusFilterData = ref([
  { text: "正常", value: 0, checked: true },
  { text: "禁用", value: 1 },
  { text: "审核中", value: 2 },
  { text: "审核拒绝", value: 3 },
]);

// 状态值转文本映射
const statusValueToText = computed(
  () => enumConverter.status_valuetotext || {}
);

// 导出Excel配置
const exportExcel = reactive({
  filename: "uni-id-users.xls",
  type: "xls",
  fields: {
    用户名: "username",
    手机号码: "mobile",
    用户状态: "status",
    邮箱: "email",
    角色: "role",
    last_login_date: "last_login_date",
  },
});

const exportExcelData = ref([]);
const noAppidWhatShouldIDoLink =
  "https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=makeup-dcloud-appid";

// 加载数据
const loadData = async () => {
  loading.value = true;
  error.value = "";

  try {
    const res = await vk.callFunction({
      url: "admin/system/user/sys/getList",
      data: {
        ...queryParams,
        pageIndex: pagination.current,
        pageSize: pagination.size,
      },
    });

    if (res.code === 0) {
      dataList.value = res.data.list || [];
      pagination.count = res.data.total || 0;

      // 处理导出数据
      exportExcelData.value = dataList.value.map((item) => {
        return {
          ...item,
          role: item.role_display || item.role,
          last_login_date: $formatDate
            ? $formatDate(item.last_login_date)
            : item.last_login_date,
        };
      });
    } else {
      error.value = res.msg || "加载失败";
      vk.toast(res.msg || "加载失败");
    }
  } catch (err) {
    error.value = err.msg || "加载失败";
    vk.toast(err.msg || "加载失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  queryParams.keyword = query.value.trim();
  pagination.current = 1;
  loadData();
};

// 分页改变
const handlePageChanged = (e) => {
  selectedIndexs.value = [];
  if (tableRef.value) {
    tableRef.value.clearSelection();
  }
  pagination.current = e.current;
  loadData();
};

// 改变每页数量
const handleChangeSize = (pageSize) => {
  pagination.size = pageSize;
  pagination.current = 1;
  loadData();
};

// 排序改变
const handleSortChange = (e, name) => {
  if (e.order) {
    queryParams.orderBy = name;
    queryParams.orderType = orderByMapping[e.order] || "desc";
  } else {
    queryParams.orderBy = "last_login_date";
    queryParams.orderType = "desc";
  }
  if (tableRef.value) {
    tableRef.value.clearSelection();
  }
  loadData();
};

// 筛选改变
const handleFilterChange = (e, name) => {
  if (name === "status") {
    if (e.filter && e.filter.length > 0) {
      queryParams.status = e.filter[0];
    } else {
      queryParams.status = undefined;
    }
  } else if (e.filter && e.filter.length > 0) {
    queryParams.keyword = e.filter[0];
  } else if (name !== "status") {
    queryParams.keyword = "";
  }

  pagination.current = 1;
  loadData();
};

// 导航
const handleNavigateTo = (url, clear = true) => {
  uni.navigateTo({
    url,
    events: {
      refreshData: () => {
        if (clear) {
          pagination.current = 1;
        }
        loadData();
      },
    },
  });
};

// 获取选中的项
const getSelectedItems = () => {
  return selectedIndexs.value.map((i) => dataList.value[i]._id);
};

// 批量删除
const handleBatchDelete = async () => {
  const ids = getSelectedItems();
  if (!ids || ids.length === 0) {
    vk.toast("请选择要删除的用户");
    return;
  }

  const confirm = await vk.confirm("确定要删除选中的用户吗？");
  if (!confirm) return;

  try {
    const res = await vk.callFunction({
      url: "admin/system/user/sys/batchDelete",
      data: { ids },
    });

    if (res.code === 0) {
      vk.toast("删除成功");
      if (tableRef.value) {
        tableRef.value.clearSelection();
      }
      loadData();
    } else {
      vk.toast(res.msg || "删除失败");
    }
  } catch (err) {
    vk.toast(err.msg || "删除失败");
  }
};

// 多选改变
const handleSelectionChange = (e) => {
  selectedIndexs.value = e.detail.index;
};

// 确认删除
const handleConfirmDelete = async (id) => {
  const confirm = await vk.confirm("确定要删除该用户吗？");
  if (!confirm) return;

  try {
    const res = await vk.callFunction({
      url: "admin/system/user/sys/delete",
      data: { _id: id },
    });

    if (res.code === 0) {
      vk.toast("删除成功");
      if (tableRef.value) {
        tableRef.value.clearSelection();
      }
      loadData();
    } else {
      vk.toast(res.msg || "删除失败");
    }
  } catch (err) {
    vk.toast(err.msg || "删除失败");
  }
};

// uni-app 页面生命周期
// 页面加载
const onLoad = (options = {}) => {
  const userId = options.id;
  if (userId) {
    queryParams.keyword = userId;
  }
  loadData();
};

const onReady = () => {
  if (dataList.value.length === 0 && !loading.value) {
    loadData();
  }
};
</script>

